package common.lib.misc;

import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

public class SRSDexception implements Thread.UncaughtExceptionHandler {

	private Thread.UncaughtExceptionHandler defaultUEH;

	private Activity app = null;

	public SRSDexception(Activity app) {
		this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
		this.app = app;

	}

	public void uncaughtException(Thread t, Throwable e) 
	{   

		StackTraceElement[] arr = e.getStackTrace();
		String Raghav =t.toString();
		String report = e.toString()+"\n\n";
		report += "--------- Stack trace ---------\n\n"+Raghav;
		for (int i=0; i<arr.length; i++)
		{
			report += "    "+arr[i].toString()+"\n";
		}
		report += "-------------------------------\n\n";

		// If the exception was thrown in a background thread inside
		// AsyncTask, then the actual exception can be found with getCause
		report += "--------- Cause ---------\n\n";
		Throwable cause = e.getCause();
		if(cause != null) {
			report += cause.toString() + "\n\n";
			arr = cause.getStackTrace();
			for (int i=0; i<arr.length; i++)
			{
				report += "    "+arr[i].toString()+"\n";
			}
		}
		report += "-------------------------------\n\n";

		try {
			FileOutputStream trace = app.openFileOutput(
					"stack.trace", Context.MODE_PRIVATE);
			trace.write(report.getBytes());
			trace.close();
			Log.i("chatify", report);
		} catch(IOException ioe) {
			// ...
		}

		defaultUEH.uncaughtException(t, e);
	}

}
